﻿using System;
using System.Collections.Generic;
using Framework.Entities;
using Framework.Interfaces;

namespace Framework.Business
{
    public class ServiceContextBase<TRequest, TResponse> : ILogRecorder
        where TRequest : class, IRequestID
        where TResponse : EnhancedSimpleResponse
    {
        public static readonly Dictionary<string, string> SeverityMapping =
            new Dictionary<string, string>
            {
                {Constants.LogTypeInformation, "INFO"},
                {Constants.LogTypeError, "ERRO"},
                {Constants.LogTypeDebug, "DBUG"},
                {Constants.LogTypeWarning, "WARN"}
            };
        public TRequest Request { get; private set; }
        public TResponse Response { get; private set; }

        public string RawInputString { get; set; }

        public ServiceContextBase(TRequest request, TResponse response)
        {
            Request = request;
            Response = response;
        }
        public void Log(string message)
        {
            Log(Constants.LogTypeInformation, message);
        }

        public void Error(string message)
        {
            Log(Constants.LogTypeError, message);
        }

        public void Debug(string message)
        {
            Log(Constants.LogTypeDebug, message);
        }

        public void Warn(string message)
        {
            Log(Constants.LogTypeWarning, message);
        }

        private void Log(string type, string msg)
        {
            var logTime = DateTime.Now;
            LogToResponse(logTime, type, msg);
        }

        private void LogToResponse(DateTime logTime, string type, string message)
        {
            if (Response.Logs == null) Response.Logs = new List<string>();

            var content = string.Format("[{0}] [{1}] {2}",
                logTime.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                SeverityMapping[type],
                message);

            Response.Logs.Add(content);
        }
    }
}
